package dao;

import bean.AddCenter;
import domain.Admin;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface AdminDao {
    //根据用户名查询
    @Select("select * from admin where username=#{username}")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "roles",column = "id" ,many = @Many(select = "dao.RoleDao.findByAdminId"))
    })
    Admin findByUsername(String username);

    //查询所有
    @Select("<script>" +
            "select * from admin " +
            " <where>" +
//            "<if test='status != null'>" +
//            " status=#{status}" +
//            "</if>" +
//            "<if test='username != null and username.length != 0'>" +
//            " and username like #{username}" +
//            "</if>" +
            "</where>" +
            " order by id desc" +
            "</script>")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "roles",column = "id" ,many = @Many(select = "dao.RoleDao.findByAdminId"))
    })
    List<Admin> findAll(Admin admin);

    //新增用户
    @Insert("insert into admin values(null,#{username},#{password},#{tel},#{email},#{status})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")//新增后返回自增id
    void add(Admin admin);

    //新增中间表admin_role数据
    @Insert("insert into admin_role values(#{num1},#{num2})")
    void addAdim_Role(AddCenter addCenter);


    //根据id查询
    @Select("select * from admin where id=#{id}")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "roles",column = "id" ,many = @Many(select = "dao.RoleDao.findByAdminId"))
    })
    Admin findById(int id);

    //根据roleId查询
    @Select("select * from admin where id IN (select adminId from admin_role where roleId = #{roleId})")
    List<Admin> findByRoleId(int roleId);

    //修改用户状态
    @Update("update admin set status = #{status} where id=#{id}")
    void updateStatus(Admin admin);

    //修改用户信息
    @Update("update admin set username=#{username},tel=#{tel},email=#{email},status=#{status} where id=#{id}")
    void update(Admin admin);

    //修改职位时先删除相关id的中间表，提交再重新添加
    @Delete("delete from admin_role where adminId = #{id}")
    void deleteAdminRole(int id);

    //设置密码
    @Update("update admin set password=#{password} where id=#{id}")
    void updatePassword(Admin admin);
}
